package com.wzu.zlb.ems.controller;


import com.wzu.zlb.ems.pojo.User;
import com.wzu.zlb.ems.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class UserAction {

    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String longin_index(HttpSession session, Model model){

        return "login";
    }

    @GetMapping("/home")
    public String goToHome(HttpSession session,Model model){
        return "home";
    }


    @PostMapping("/user/login")
    public  String login(User user, HttpSession session, Model model){

        Subject subject = SecurityUtils.getSubject();
        //封装用户数据

        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserCode(),user.getUserPassword());
        try {
            subject.login(token);
            User loginUser = userService.findUserByCode(user.getUserCode());
            session.setAttribute("userinfo", loginUser);
            return "redirect:/home";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg","用户名错误！");
            return "login";
        } catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误！");
            e.printStackTrace();
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String tuichu(User user, HttpSession session){
        System.out.println("退出系统成功");

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }
}
